#include <stdint.h>
#include <stdio.h>

typedef struct datetime_t {
    uint32_t  year;
    uint32_t  mon;
    uint32_t  day;
    uint32_t  hour;
    uint32_t  min;
    uint32_t  sec;
} DateTime_T;

#define SECONDS_PER_HOUR    3600
#define SECONDS_PER_DAY     86400
#define SECONDS_365_DAY     31536000
#define SECONDS_366_DAY     31622400

static uint32_t month_seconds[] = {
    31 * SECONDS_PER_DAY,
    28 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY,
    30 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY,
    30 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY,
    30 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY,
    30 * SECONDS_PER_DAY,
    31 * SECONDS_PER_DAY
};

void  sysUTC_To_DOS_Time(uint32_t utc, DateTime_T *dos_tm)
{
    int     the_year = 1970;
    int     i, seconds;

    while (1) {
        if (the_year % 4 == 0)
            seconds = SECONDS_366_DAY;
        else
            seconds = SECONDS_365_DAY;
        if (utc >= seconds) {
            utc -= seconds;
            the_year++;
        } else
            break;
    }

    dos_tm->year = the_year;

    if (the_year % 4 == 0)
        month_seconds[1] = 29 * SECONDS_PER_DAY;
    else
        month_seconds[1] = 28 * SECONDS_PER_DAY;

    dos_tm->mon = 1;
    for (i = 0; i < 11; i++) {
        if (utc >= month_seconds[i]) {
            utc -= month_seconds[i];
            dos_tm->mon++;
        } else
            break;
    }

    dos_tm->day = 1 + (utc / SECONDS_PER_DAY);
    utc %= SECONDS_PER_DAY;

    dos_tm->hour = utc / SECONDS_PER_HOUR;
    utc %= SECONDS_PER_HOUR;

    dos_tm->min = utc / 60;
    dos_tm->sec = utc % 60;
}


int main(int argc, char** argv) {
    uint32_t t = 1681179460;
    if( argc > 1) {
        t = atol(argv[1]);
    }
    printf("argc = %d\n", t);

    DateTime_T dos_tm = {0};
    sysUTC_To_DOS_Time(t, &dos_tm);
    
    printf("year = %d\n", dos_tm.year);
    printf("mon = %d\n", dos_tm.mon);
    printf("day = %d\n", dos_tm.day);
    printf("hour = %d\n", dos_tm.hour);
    printf("min = %d\n", dos_tm.min);
    printf("sec = %d\n", dos_tm.sec);
}



